﻿using System;
using System.Web.UI.WebControls;
using PBOffice.BLL;

public partial class Controls_DepartmentSelector : System.Web.UI.UserControl
{
	public event EventHandler ValueChanged;

	protected void Page_Load(object sender, EventArgs e)
	{
		if (IsPostBack) return;
		// 使用部门数据填充TreeView
		var organs = new OrganManager();
		foreach (var organ in organs.ShowAllOrganInfo())
		{
			TreeNode root = new TreeNode(organ.OrganShortName ?? organ.OrganId, organ.OrganNo.ToString());
			var depart = new DepartmentManager();
			var deps = depart.ShowDepInfoByOrganNo(organ.OrganNo);
			foreach (var dep in deps)
			{
				TreeNode subTN = new TreeNode(dep.DepDescribe ?? dep.DepId, dep.DepNo.ToString());
				addSubDeparts(subTN, dep.DepNo);
				root.ChildNodes.Add(subTN);
			}
			tvDepartSelector.Nodes.Add(root);
		}
	}

	private void addSubDeparts(TreeNode tn, int depNo)
	{
		var depart = new DepartmentManager();
		var subDeparts = depart.GetSubDepartments(depNo);
		foreach (var subDepart in subDeparts)
		{
			TreeNode subTN = new TreeNode(subDepart.DepDescribe ?? subDepart.DepId, subDepart.DepNo.ToString());
			addSubDeparts(subTN, subDepart.DepNo);
			tn.ChildNodes.Add(subTN);
		}
	}

	/// <summary>
	/// 获取用户选择的文本
	/// </summary>
	public string SelectedText { get { return ViewState["selectedText"] as string; } }

	/// <summary>
	/// 获取用户选择的值
	/// </summary>
	public string SelectedValue { get { return ViewState["selectedValue"] as string; } }

	public bool Enabled
	{
		get { return tbDepartment.Enabled; }
		set { tbDepartment.Enabled = value; }
	}

	protected void tvDepartSelector_SelectedNodeChanged(object sender, EventArgs e)
	{
		var tn = tvDepartSelector.SelectedNode;
		if (tn.ChildNodes.Count == 0 && tn.Parent != null) //只允许叶子节点的值作为结果返回
		{
			ViewState["selectedText"] = tn.Text;
			ViewState["selectedValue"] = tn.Value;
			tbDepartment.Text = tn.Text;
		}
		ValueChanged(sender, e);
	}
}